package hr.ctg.security;

import hr.ctg.domain.model.Korisnik;
import hr.ctg.domain.model.Rola;

import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Identity;

@Name("clientAuthenticator")
public class ClientAuthenticator {

	@In
	EntityManager entityManager;

	@In
	Identity identity;

	@Out(required = false, scope = ScopeType.SESSION)
	Korisnik korisnik;

	@Logger
	Log log;

	public boolean authenticate() {
		boolean autenticated = false;
		String username = identity.getUsername();
		log.debug("authenticating {0}", username);

		try {
			korisnik = (Korisnik) entityManager.createNamedQuery(
					"Korisnik.findByUsernamePasswordAktivan").setParameter(1,
					username).setParameter(2, identity.getPassword())
					.setParameter(3, true).getSingleResult();

			log.debug("korisnik {0} trazi pristup...", username);

			if (korisnik != null) {
				log.debug("korisnik {0} ima pristup...", korisnik.getEmail());
				for (final Rola r : korisnik.getRolas()) {
					identity.addRole(r.getIdRole().toString());
				}
				autenticated = true;
			}
		} catch (final EntityNotFoundException ex) {
			log.debug("korisnik {0} ne postoji...", username);
			return false;
		} catch (final javax.persistence.NoResultException ex) {
			log.debug("korisnik {0} ne postoji...", username);
			return false;
		}

		return autenticated;
	}
}
